package cn.witsky.rtp2ws.domain;

import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;

public class RtpCached {
	private static Logger logger = LoggerFactory.getLogger(RtpCached.class);
	//缓存数据
	private Map<Integer, Message> cache = new HashMap<Integer, Message>();
	//数据量长度
	private int rtpDataSize=0;
	private volatile ByteBuf buf=Unpooled.buffer(0);
	private volatile boolean isFinish=false;
	private String rtpId="";
	public RtpCached(String rtpId){
		this.rtpId=rtpId;
	}
//	void addMessage(Message message) {
//		if(message.getSeq()<0) {
//			return;
//		}
//		rtpDataSize++;
//		message.setIndex(rtpDataSize);
//		logger.debug("call:{} message:{}",message.getCallId(),message);
//		cache.put(message.getIndex(), message);
//	}
	
	void addMessage(Message message) {
		if(isFinish) {
			logger.warn("task:{}已经结束了,丢弃message:{}",this.rtpId,message);
		}else {
			if(message.getSeq()<0) {
				logger.warn("task:{}收到了结束事件",this.rtpId);
				isFinish=true;
			}
		}
		if(!isFinish) {
			rtpDataSize++;
			message.setIndex(rtpDataSize);
			logger.debug("call:{} message:{}",message.getCallId(),message);
			cache.put(message.getIndex(), message);
		}

	}
	
	
	int getRtpDataSize() {
		return rtpDataSize;
	}
	
	Message getMessage(int index) {
		return cache.get(index);
	}

	int size() {
		return cache.size();
	}
	
	public void bufWrite(String rtpId,byte[] bytes) {
		if(buf!=null) {
			try {
				buf.writeBytes(bytes);
			}catch(Exception ex) {
				logger.error("task:"+rtpId+" bufWrite出现异常", ex);
			}
		}else {
			buf=Unpooled.buffer(0);
		}
	}
	
	public void bufRead(byte[] bytes) {
		buf.readBytes(bytes);
		buf.clear();
		buf.retain();
	}
	
	
	public int  getByteSzie() {
		if(buf==null) {
			return 0;
		}
		int writeIndex=buf.writerIndex();
		int readIndex=buf.readerIndex();
		return writeIndex-readIndex;
	}
	
//	public  void clearBuf() {
//		buf.clear();
//		buf.retain();
//	}

	public  void bufRelease(String rtpId) {
		logger.debug("task:"+rtpId+" buf释放了......");
		if(buf!=null) {
			buf.release();
			buf=null;
		}

	}
	
	public ByteBuf getBuf() {
		return buf;
	}
	
}
